package com.itheima.health.controller;

import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Order;
import com.itheima.health.service.OrderService;
import com.itheima.health.utils.pay.PayUtils;
import com.itheima.health.utils.redis.RedisUtil;
import com.itheima.health.utils.resources.RedisMessageConstant;
import com.itheima.health.utils.sms.ValidateCodeUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("order")
@Api(tags = "移动端订单管理")
public class OrderController {

    @Reference(timeout = 1500,mock = "com.itheima.health.service.OrderServiceMock")
    private OrderService orderService;

    @GetMapping("sendCode/{telephone}")
    @ApiOperation(value = "发送验证码", notes = "根据手机号，发送验证码给用户手机")//   添加业务方法上
    public Result sendCode(@PathVariable("telephone") String telephone) {
        //使用工具类获取要发送的验证码
        String code = ValidateCodeUtils.generateValidateCode(4);
        //给用户手机发送验证码
        //SmsUtils.validUserTelephone(telephone, code);
        System.out.println("验证码" + code);
        RedisUtil.set(RedisMessageConstant.SENDTYPE_ORDER + telephone, code, 60, TimeUnit.SECONDS);//存60秒
        return new Result(code);
    }

    @PostMapping("add")
    @ApiOperation(value = "预约", notes = "根据用户提交的表单，进行预约服务")//   添加业务方法上
    public Result add(@RequestBody Map map) throws InterruptedException {//使用map来接收表单数据
        Order order = orderService.add(map);

        String pay_url = PayUtils.createOrder(order.getId() + "", 1);
        System.out.println("pay_url = " + pay_url);
        HashMap<Object, Object> Retmap = new HashMap<>();
        Retmap.put("id",order.getId());
        Retmap.put("pay_url",pay_url);
        return new Result(Retmap);
    }

    @GetMapping("selectOrderInfoByOrderId/{id}")
    @ApiOperation(value = "订单信息", notes = "根据用户提交的订单Id，查询订单信息显示在页面")//   添加业务方法上
    public Result selectOrderInfoByOrderId(@PathVariable("id") Integer id) {//使用map来接收表单数据
        return new Result(orderService.selectOrderInfoByOrderId(id));
    }

    //微信支付 todoby dzf
    @RequestMapping(value="payNotify",method=RequestMethod.POST)
    public Result createUrl(HttpServletRequest request, HttpServletResponse response) throws IOException {

        // 1.接收请求参数（xml）
        ServletInputStream in = request.getInputStream();
        // 2.将xml转为java对象
        XmlMapper xmlMapper = new XmlMapper();

        Map param = xmlMapper.readValue(in, Map.class);

        orderService.updateByOrderId(Integer.parseInt(param.get("out_trade_no")+"") );
        System.out.println("success====================");
        return new Result("支付成功");
    }


    @GetMapping("findState/{id}")
    public Result findState(@PathVariable("id")Integer id) {

        Integer state = orderService.findState(id);
        System.out.println("state = " + state);
        if(state>0)
            return new Result();
        else
            return new Result(false,"等待交易");
    }


}
